package com.example.springboot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Constants;
import com.example.springboot.mapper.MessageMapper;
import com.example.springboot.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;
import com.example.springboot.common.Result;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.example.springboot.service.IMessageService;
import com.example.springboot.entity.Message;

import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/message")
    public class MessageController {
    
    @Resource
    private IMessageService messageService;
    @Resource
    private MessageMapper messageMapper;

    //新增或更新
    @PostMapping
    public Result save(@RequestBody Message message) {
        boolean result = messageService.saveOrUpdate(message);
        if (result)
            return Result.success(true);
        else
            return Result.error(Constants.CODE_600,"发送失败");
    }

    //查找当前用户所有
    @GetMapping
    public Result findAll() {
        return Result.success(messageService.getByUser(Objects.requireNonNull(TokenUtils.getCurrentUser()).getId()));
    }

    //获取当前用户未读消息数
    @GetMapping("/getUnReadCount")
    public Result getUnReadCount(){
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",Objects.requireNonNull(TokenUtils.getCurrentUser()).getId());
        queryWrapper.eq("statement","未读");
        List<Message> messageList = messageService.list(queryWrapper);
        return Result.success(messageList.size());
    }

    //将消息状态改为已读
    @PostMapping("/readAll")
    public Result readAll(){
        if (messageMapper.readAll(Objects.requireNonNull(TokenUtils.getCurrentUser()).getId()))
            return Result.success("修改成功");
        else
            return Result.error();
    }


}

